# -*- coding: utf-8 -*-
# @FileName : My.py
# @Time     : 2023/6/11 22:30
# @Author   : Zhong Runke
from web.controller.api import route_api
from common.models.Goods import Goods
from flask import jsonify, request
from common.models.User import User
from common.libs.UrlManager import UrlManager
from common.models.Order import Order
from common.models.OrderItem import OrderItem
from common.libs.Helper import selectFilterObj, getDictFilterField


@route_api.route('/my/order')
def myOrderList():
    resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
    auth_cookie = request.headers.get("Authorization")
    print(auth_cookie)
    auth_info = auth_cookie.split("#")
    user_info = User.query.filter_by(id=auth_info[1]).first()
    if not user_info:
        resp['code'] = -1
        resp['msg'] = '数据库查询错误'
        return jsonify(resp)

    req = request.values
    status = int(req['status']) if 'status' in req else 0
    query = Order.query.filter_by(buyer=user_info.address)
    if status == -8:  # 等待付款
        query = query.filter(Order.status == -8)
    elif status == -7:  # 待发货
        query = query.filter(Order.status == 1, Order.express_status == -7)
    elif status == -6:  # 待确认
        query = query.filter(Order.status == 1, Order.express_status == -6)
    elif status == -5:  # 待评价
        query = query.filter(Order.status == 1, Order.express_status == 1)
    elif status == 1:  # 已完成
        query = query.filter(Order.status == 1, Order.express_status == 1)
    else:
        query = query.filter(Order.status == 0)

    pay_order_list = query.order_by(Order.id.desc()).all()
    print(pay_order_list)
    data_pay_order_list = []
    if pay_order_list:
        pay_order_ids = selectFilterObj(pay_order_list, "id")
        print(pay_order_ids)
        pay_order_item_list = OrderItem.query.filter(OrderItem.order_id.in_(pay_order_ids)).all()
        good_ids = selectFilterObj(pay_order_list, "goodsNumber")
        print(good_ids)
        good_map = getDictFilterField(Goods, Goods.id, "id", good_ids)
        print(good_map)
        pay_order_item_map = {}
        if pay_order_item_list:
            for item in pay_order_item_list:
                if item.order_id not in pay_order_item_map:
                    pay_order_item_map[item.order_id] = []
                tmp_good_info = good_map[item.good_id]
                pay_order_item_map[item.order_id].append({
                    "id": item.id,
                    "good_id": item.good_id,
                    "quantity": item.quantity,
                    "price": str(item.price),
                    "pic_url": UrlManager.buildImageUrl(tmp_good_info.image),
                    "name": tmp_good_info.name
                })
        # 遍历订单
        for item in pay_order_list:

            tmp_data = {
                'status': item.pay_status,
                'status_desc': item.status_desc,
                'date': item.created_time.strftime("%Y-%m-%d %H:%M:%S"),
                'order_number': item.order_number,
                'order_sn': item.order_sn,
                'note': item.note,
                'total_price': str(item.price),
                'goods_list': pay_order_item_map[item.id]
            }
            data_pay_order_list.append(tmp_data)
    resp['data']['pay_order_list'] = data_pay_order_list
    return jsonify(resp)


@route_api.route("/my/releaseList", methods=["GET", "POST"])
def myReleaseList():
    resp = {'code':200, 'msg': 'OK', 'data':{}}
    req = request.values
    curType = int(req['curType']) if 'curType' in req else None
    if curType is None and curType not in [1, 0]:
        resp['code'] = -1
        resp['msg'] = '参数错误'
        return jsonify(resp)
    # 登录校验
    auth_cookie = request.headers.get("Authorization")
    auth_info = auth_cookie.split("#")
    user_info = User.query.filter_by(id=auth_info[1]).first()
    if not user_info:
        resp['code'] = -1
        resp['msg'] = '数据库查询错误'
        return jsonify(resp)

    if not curType:
        goods_list = Goods.query.filter_by(useraddress=user_info.address, status=1).order_by(Goods.id.desc()).all()
    else:
        goods_list = Goods.query.filter_by(useraddress=user_info.address, status=0).order_by(Goods.id.desc()).all()
    goods_infos = []
    for goods in goods_list:
        goods_dict = {
            "id": goods.id,
            "name": goods.name,
            "image": UrlManager.buildImageUrl(goods.image),
            "price": str(goods.price),
            "blockHash": goods.blockHash
        }
        goods_infos.append(goods_dict)

    resp['data']['goods_list'] = goods_infos
    return jsonify(resp)


@route_api.route("/my/saleGoodsList", methods=['GET', 'POST'])
def mySaleGoodsList():
    resp = {'code': 200, 'msg': 'OK', 'data': {}}
    req = request.values
    print("++++++++++++++++++++++++++++++++++++++")
    print(req)
    curType = int(req['curType']) if 'curType' in req else -1
    # 登录校验
    auth_cookie = request.headers.get("Authorization")
    auth_info = auth_cookie.split("#")
    user_info = User.query.filter_by(id=auth_info[1]).first()
    if not user_info:
        resp['code'] = -1
        resp['msg'] = '数据库查询错误'
        return jsonify(resp)

    query = Order.query.filter_by(seller=user_info.address)
    if curType == 0:
        pass
    elif curType == 1:
        # 待付款
        query = query.filter(Order.status == -8)
    elif curType == 2:
        #
        query = query.filter(Order.status == 1, Order.express_status == -7)
    elif curType == 3:
        query = query.filter(Order.status == 1, Order.express_status == -6)
    elif curType == 4:
        query = query.filter(Order.status == 1, Order.express_status == 1)

    pay_order_list = query.order_by(Order.id.desc()).all()
    print(pay_order_list)
    data_pay_order_list = []
    if pay_order_list:
        pay_order_ids = selectFilterObj(pay_order_list, "id")
        pay_order_item_list = OrderItem.query.filter(OrderItem.order_id.in_(pay_order_ids)).all()
        # 获取所有商品id
        good_ids = selectFilterObj(pay_order_list, "goodsNumber")
        # 建立商品映射
        good_map = getDictFilterField(Goods, Goods.id, "id", good_ids)
        print(good_map)
        pay_order_item_map = {}
        if pay_order_item_list:
            for item in pay_order_item_list:
                if item.order_id not in pay_order_item_map:
                    pay_order_item_map[item.order_id] = []
                tmp_good_info = good_map[item.good_id]
                pay_order_item_map[item.order_id].append({
                    "id": item.id,
                    "good_id": item.good_id,
                    "quantity": item.quantity,
                    "price": str(item.price),
                    "pic_url": UrlManager.buildImageUrl(tmp_good_info.image),
                    "name": tmp_good_info.name
                })
        # 遍历订单
        for item in pay_order_list:
            tmp_data = {
                'status': item.pay_status,
                'status_desc': item.status_desc,
                'date': item.created_time.strftime('%Y-%m-%d %H:%M:%S'),
                'order_number': item.order_number,
                'order_sn': item.order_sn,
                'note': item.note,
                'total_price': str(item.price),
                'goods_list': pay_order_item_map[item.id]
            }
            data_pay_order_list.append(tmp_data)

    resp['data']['pay_order_list'] = data_pay_order_list
    return jsonify(resp)


